//
//  JXChatListCtl.m
//  JiaoX
//
//  Created by yinqy on 15/3/18.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  最近聊天列表

#import "JXChatListCtl.h"
#import "JXChatManager.h"
#import "Conversation.h"
#import "RecentChatCell.h"
#import "JXChatCtl.h"
#import "DeleteBottomView.h"

@interface JXChatListCtl ()<UITableViewDataSource,UITableViewDelegate,DeleteBottomViewDelegate>
@property (nonatomic,strong)NSMutableArray *conversions;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)DeleteBottomView *bottomView;
@end

@implementation JXChatListCtl

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
    self.conversions = [NSMutableArray array];
    
}

-(void)setupView{
    self.title = @"私信";
    [self.view setBackgroundColor:JXGlobalColorBg];
    
    JXLog(@"%@",NSStringFromCGRect(self.view.frame));
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    self.tableView.allowsSelectionDuringEditing = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setTableFooterView:[[UIView alloc]init]];
    [self.view addSubview:self.tableView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessageCome:) name:NOTI_NEW_MESSAGE object:nil];
    [self queryData];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTI_NEW_MESSAGE object:nil];
}

#pragma mark - tableview

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.conversions.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RecentChatCell *cell = [RecentChatCell cellWithTableView:tableView];
    Conversation *con = self.conversions[indexPath.row];
    [cell setChecked:con.checked];
    [cell.recentChatCellView setConverstaion:con];
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return CELLVIEW_HEIGHT;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    Conversation *con = self.conversions[indexPath.row];
    if (!self.tableView.editing)
    {
        JXChatCtl *ctl = [[JXChatCtl alloc]initWithUserInfo:con.toUser];
        [self.navigationController pushViewController:ctl animated:YES];
    }else{
        RecentChatCell *cell = (RecentChatCell*)[tableView cellForRowAtIndexPath:indexPath];
        con.checked = !con.checked;
        [cell setChecked:con.checked];
        [self.bottomView setSelect:[self isSelectAll]];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}

#pragma mark - 私有方法
-(void)editConversations{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    [self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.3];
    if (self.tableView.editing) {
        //是编辑模式
        if (!self.bottomView) {
            self.bottomView = [[DeleteBottomView alloc]init];
            self.bottomView.y = self.view.height-self.bottomView.height;
            [self.bottomView setDelegate:self];
            [self.view addSubview:self.bottomView];
        }
        [self.bottomView setHidden:NO];
        
        [self.tableView setHeight:self.view.height-49];
    }else{
        //不是编辑模式
        [self.bottomView setHidden:YES];
        [self.tableView setHeight:self.view.height];
    }
}

-(BOOL)isSelectAll{
    BOOL result = YES;
    for (Conversation *con in self.conversions) {
        if (!con.checked) {
            return NO;
        }
    }
    return result;
}

-(void)selectAllBtnClick:(UIButton *)btn{
    if (btn.selected) {
        //全选
        [self.conversions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            Conversation *con = obj;
            [con setChecked:YES];
        }];
    }else{
        //取消全选
        [self.conversions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            Conversation *con = obj;
            [con setChecked:NO];
        }];
    }
    [self.tableView reloadData];
}

-(void)deleteBtnClick{
    //删除选中的条目
    for (Conversation *con in self.conversions) {
        if (con.checked) {
            [[JXChatManager sharedInstance].chatMsgDao deleteSessionWithId:con.toUser.userId type:RoomTypeSingle];
            [[JXChatManager sharedInstance].chatMsgDao deleteMessageWithOtherId:con.toUser.userId];
        }
    }
    [self queryData];
    [self editConversations];
}
-(void)newMessageCome:(NSNotification *)noti{
    [self queryData];
}

-(NSArray *)shortArray:(NSArray *)array{
    NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(Conversation *con1, Conversation *con2){
        return [[NSString stringWithFormat:@"%lld",con2.msg.timestamp] compare:[NSString stringWithFormat:@"%lld",con1.msg.timestamp]];
    }];
    return sortedArray;
}

-(void)queryData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.conversions removeAllObjects];
        [self.conversions addObjectsFromArray:[self shortArray:[[JXChatManager sharedInstance].chatMsgDao getConversionsWithOwnerId:CURRENTUSERID]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showNullView:!self.conversions.count];
            [self.tableView reloadData];
        });
    });
}

-(void)showNullView:(BOOL)show{
    if (show) {
        self.navigationController.navigationItem.rightBarButtonItem = nil;
        
        [self.tableView removeFromSuperview];
        //添加nullview
        
        UIView *nullView = [[UIView alloc]init];
        
        UILabel *label = [[UILabel alloc]init];
        [label setTextColor:[UIColor blackColor]];
        [label setText:@"还没有私信"];
        [label setTextAlignment:NSTextAlignmentCenter];
        [label setFont:[UIFont systemFontOfSize:[DimensUtils getScaleX:16]]];
        [label setSize:[label.text sizeWithFont:label.font]];
        [label setWidth:label.width+20];
        [nullView addSubview:label];
        
        UIButton *btn = [[UIButton alloc]init];
        [btn addTarget:self action:@selector(toChat) forControlEvents:UIControlEventTouchUpInside];
        [btn setFrame:CGRectMake(0, CGRectGetMaxY(label.frame)+10, label.width,[DimensUtils getScaleX:34])];
        [btn.layer setCornerRadius:5];
        [btn.layer setBorderWidth:1];
        [btn.layer setMasksToBounds:YES];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:[DimensUtils getScaleX:15]]];
        [btn.layer setBorderColor:[JXThemeColor CGColor]];
        [btn setTitle:@"找人聊聊" forState:UIControlStateNormal];
        [btn setTitleColor:JXThemeColor forState:UIControlStateNormal];
        [nullView addSubview:btn];
        
        nullView.size = CGSizeMake(btn.width, CGRectGetMaxY(btn.frame));
        nullView.center = self.view.center;
        nullView.tag = 1000;
        [self.view addSubview:nullView];
    }else{
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:self action:@selector(editConversations)];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        
        
        UIView *view = [self.view viewWithTag:1000];
        if (view) {
            [view removeFromSuperview];
            [self.view addSubview:self.tableView];
        }
        
    }
}

-(void)toChat{
    [self.navigationController popToRootViewControllerAnimated:NO];
}

-(BOOL)shouldLogin{
    return YES;
}

@end
